package com.app.android.coliy.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.app.android.coliy.R;
import com.app.android.coliy.constant.Constants;
import com.app.android.coliy.constant.SPConstants;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.interface_.OkHttpCallBack;
import com.app.android.coliy.manager.API_LoginManager;
import com.app.android.coliy.manager.UserManager;
import com.app.android.coliy.responce.BaseResponce;
import com.app.android.coliy.responce.CommResponce;
import com.app.android.coliy.responce.LoginResponce;
import com.app.android.coliy.tool.CommLoading;
import com.app.android.coliy.tool.CommToast;
import com.app.android.coliy.tool.SPUtil;
import com.app.android.coliy.ui.view.Comm_EditView;
import com.app.android.coliy.ui.view.Comm_SubmitBtnView;
import com.app.android.coliy.ui.view.MultiStateView;
import com.app.android.coliy.util.Util;

//import cn.smssdk.EventHandler;
//import cn.smssdk.SMSSDK;


/**
 * Created by Administrator on 2018/6/20.
 * 注册-提交
 */

public class Regist_SubmitActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        type = getIntent().getIntExtra("typeName", 0);
        setContentView(R.layout.activity_regist_submit);
        initView();
    }

    int type = 0;   // 0 ：注册  1：设置密码    2：绑定手机号    3：绑定邮箱     4：设置支付密码    5：修改支付密码

    MultiStateView multiplestatusView;
    TextView tv_sendcode, tv_action_name, tv_action_tips;
    Comm_SubmitBtnView tv_regist;
    Comm_EditView et_pwd1, et_pwd2, et_invitecode, et_old_pwd, et_code, et_account, et_nickname;
    LinearLayout ll_yanqingma, ll_old_pwd, ll_pwd1, ll_pwd2, ll_nickname;

    //初始化控件
    private void initView() {
        setLeftImgClickListener();  //设置左键返回

        multiplestatusView = findViewById(R.id.multiplestatusView);
//        multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);    //页面初始化，默认为加载中状态
        multiplestatusView.setOnRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);
            }
        });

        et_account = findViewById(R.id.et_account);
        tv_sendcode = findViewById(R.id.tv_sendcode);
        tv_regist = findViewById(R.id.tv_regist);
        et_code = findViewById(R.id.et_code);
        et_pwd1 = findViewById(R.id.et_pwd1);
        et_pwd2 = findViewById(R.id.et_pwd2);
        et_invitecode = findViewById(R.id.et_invitecode);
        ll_yanqingma = findViewById(R.id.ll_yanqingma);
        ll_old_pwd = findViewById(R.id.ll_old_pwd);
        ll_pwd1 = findViewById(R.id.ll_pwd1);
        ll_pwd2 = findViewById(R.id.ll_pwd2);
        tv_action_name = findViewById(R.id.tv_action_name);
        tv_action_tips = findViewById(R.id.tv_action_tips);
        et_old_pwd = findViewById(R.id.et_old_pwd);
        ll_nickname = findViewById(R.id.ll_nickname);
        et_nickname = findViewById(R.id.et_nickname);

        tv_sendcode.setOnClickListener(this);
        tv_regist.setOnClickListener(this);

        // 0 ：注册  1：忘记/修改密码    2：绑定手机号    3：绑定邮箱
        ll_old_pwd.setVisibility(View.GONE);
        ll_pwd1.setVisibility(View.GONE);
        ll_pwd2.setVisibility(View.GONE);
        ll_yanqingma.setVisibility(View.GONE);
        ll_nickname.setVisibility(View.GONE);
        if (type == 0) {   // 0 ：注册
            setTitle(Util.getString(R.string.regist_title));
//            tv_regist.tv_btn.setText("立即注册");
            tv_action_name.setText("设置密码");
            tv_action_tips.setText("8-20位字符（字母+数字组合），不可以是纯数字");
            ll_pwd1.setVisibility(View.VISIBLE);
            ll_pwd2.setVisibility(View.VISIBLE);
            ll_nickname.setVisibility(View.VISIBLE);
//            ll_yanqingma.setVisibility(View.VISIBLE);
        } else if (type == 1) {   //1：忘记/修改密码
            setTitle(Util.getString(R.string.regist_title_changepwd));
//            tv_regist.tv_btn.setText("确认");
            tv_action_name.setText("设置密码");
            tv_action_tips.setText("8-20位字符（字母+数字组合），不可以是纯数字");
//            ll_old_pwd.setVisibility(View.VISIBLE);
            ll_pwd1.setVisibility(View.VISIBLE);
            ll_pwd2.setVisibility(View.VISIBLE);
        }

        et_account.setInputCallBack(inputCallback);
        et_pwd1.setInputCallBack(inputCallback);
        et_pwd2.setInputCallBack(inputCallback);
        et_invitecode.setInputCallBack(inputCallback);
        et_code.setInputCallBack(inputCallback);
        checkInput();
    }

    CommCallBack inputCallback = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            checkInput();
        }
    };

    private void checkInput() {
        tv_regist.setEnabled(false);
        if (et_account.getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_account.getText().toString())) {
            return;
        }
        if (ll_nickname.getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_nickname.getText().toString())) {
            return;
        }
        if (et_code.getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_code.getText().toString())) {
            return;
        }
        if (((LinearLayout) et_old_pwd.getParent()).getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_old_pwd.getText().toString())) {
            return;
        }
        if (((LinearLayout) et_pwd1.getParent()).getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_pwd1.getText().toString())) {
            return;
        }
        if (((LinearLayout) et_pwd2.getParent()).getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_pwd2.getText().toString())) {
            return;
        }
        if (((LinearLayout) et_invitecode.getParent()).getVisibility() == View.VISIBLE && TextUtils.isEmpty(et_invitecode.getText().toString())) {
            return;
        }
        tv_regist.setEnabled(true);
    }

    //发验证码
    private void checkPhone() {
        final String account = et_account.getText();
        if (TextUtils.isEmpty(account)) {
            CommToast.showToast(mContext, "请输入手机号");
            return;
        }

        CommLoading.showLoading(mContext);
        API_LoginManager.checkmobile(mContext, account, new OkHttpCallBack() {
            @Override
            public void onSuccess(BaseResponce baseResponce) {
                CommResponce responce = (CommResponce) baseResponce;
                if (BaseResponce.Status_Success.equals(responce.data.code)) {
                    sendCode(account);
                } else {
                    CommToast.showToast(mContext, responce.data.msg);
                }
            }

            @Override
            public void onFailure(BaseResponce baseResponce) {
                CommToast.showToast(mContext, Constants.NET_ERROR);
            }
        });
    }

    //注册
    private void regiets() {
        final String phoneOrEmail = et_account.getText();
        String nickname = et_nickname.getText();
        String code = et_code.getText().toString();
        String pwd1 = et_pwd1.getText().toString();
        String pwd2 = et_pwd2.getText().toString();
        if (!pwd2.equals(pwd1)) {
            CommToast.showToast(mContext, "两次输入的密码不一致");
            return;
        }

        CommLoading.showLoading(mContext);
        API_LoginManager.smsregister(mContext, phoneOrEmail, nickname, pwd1, code, new OkHttpCallBack() {
            @Override
            public void onSuccess(BaseResponce baseResponce) {
                LoginResponce responce = (LoginResponce) baseResponce;
                if (BaseResponce.Status_Success.equals(responce.data.code)) {
                    UserManager.saveToken(mContext, responce.data.uid);
                    SPUtil.putValue(mContext, SPConstants.Phone, phoneOrEmail);
                    CommToast.showToast(mContext, "注册成功");
                    finish();
                } else {
                    CommToast.showToast(mContext, responce.data.msg);
                }
            }

            @Override
            public void onFailure(BaseResponce baseResponce) {
                CommLoading.dismissLoading();
                CommToast.showToast(mContext, Constants.NET_ERROR);
            }
        });
    }

    //修改登录密码
    private void modifyLoginPwd() {
        String phoneNumber = et_account.getText();
        String code = et_code.getText().toString();
        String newPwd1 = et_pwd1.getText().toString();
        String newPwd2 = et_pwd2.getText().toString();
        if (!newPwd1.equals(newPwd2)) {
            CommToast.showToast(mContext, "两次输入的密码不一致");
            return;
        }
        CommLoading.showLoading(mContext);
        API_LoginManager.reset(mContext, phoneNumber, newPwd1, code, new OkHttpCallBack() {
            @Override
            public void onSuccess(BaseResponce baseResponce) {
                CommLoading.dismissLoading();
                CommResponce responce = (CommResponce) baseResponce;
                if (BaseResponce.Status_Success.equals(responce.data.code)) {
                    CommToast.showToast(mContext, "修改成功");
                    finish();
                } else {
                    CommToast.showToast(mContext, responce.data.msg);
                }
            }

            @Override
            public void onFailure(BaseResponce baseResponce) {
                CommLoading.dismissLoading();
                CommToast.showToast(mContext, Constants.NET_ERROR);
            }
        });
    }

    private void sendCode(String phone) {
//        // 注册一个事件回调，用于处理SMSSDK接口请求的结果
//        SMSSDK.registerEventHandler(eventHandler);
//
//        // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
//        SMSSDK.getVerificationCode("86", phone);
//
//        // 提交验证码，其中的code表示验证码，如“1357”
////        SMSSDK.submitVerificationCode("86", phone, code);
    }

//    EventHandler eventHandler = new EventHandler() {
//        public void afterEvent(int event, int result, Object data) {
//            // afterEvent会在子线程被调用，因此如果后续有UI相关操作，需要将数据发送到UI线程
//            Message msg = new Message();
//            msg.arg1 = event;
//            msg.arg2 = result;
//            msg.obj = data;
//            new Handler(Looper.getMainLooper(), new Handler.Callback() {
//                @Override
//                public boolean handleMessage(Message msg) {
//                    CommLoading.dismissLoading();
//                    int event = msg.arg1;
//                    int result = msg.arg2;
//                    Object data = msg.obj;
//                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//                        if (result == SMSSDK.RESULT_COMPLETE) {
//                            Log.i("发送结果：成功");
//                            // TODO 处理成功得到验证码的结果
//                            // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
//                            //发送验证码
//                            CommToast.showToast(mContext, "发送成功");
//                            handler.removeCallbacks(runnable);
//                            handler.post(runnable);
//                            et_code.requestFocus();
//                        } else {
//                            // TODO 处理错误的结果
//                            Log.i("验证结果：失败");
//                            ((Throwable) data).printStackTrace();
//                        }
//                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//                        if (result == SMSSDK.RESULT_COMPLETE) {
//                            // TODO 处理验证码验证通过的结果
//                            Log.i("验证结果：成功");
//                        } else {
//                            // TODO 处理错误的结果
//                            ((Throwable) data).printStackTrace();
//                            Log.i("验证结果：失败");
//                        }
//                    }
//                    // TODO 其他接口的返回结果也类似，根据event判断当前数据属于哪个接口
//                    return false;
//                }
//            }).sendMessage(msg);
//        }
//    };


//    // 使用完EventHandler需注销，否则可能出现内存泄漏
//    protected void onDestroy() {
//        super.onDestroy();
//        SMSSDK.unregisterEventHandler(eventHandler);
//    }

    //点击事件
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_sendcode:   //发送验证码
                checkPhone();
                break;
            case R.id.tv_regist:       //确定按钮
                if (type == 0) {
                    regiets();   //注册
                } else if (type == 1) {
                    modifyLoginPwd();  //修改密码
                }
                break;
        }
    }

    int num = 60;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            num--;
            if (num == 0) {
                tv_sendcode.setEnabled(true);
                tv_sendcode.setTextColor(Color.parseColor("#f2493a"));
                tv_sendcode.setText("发送验证码");
                num = 60;
            } else {
                tv_sendcode.setText(num + "s");
                tv_sendcode.setEnabled(false);
                tv_sendcode.setTextColor(Color.parseColor("#999999"));
                handler.postDelayed(runnable, 1000);
            }
        }
    };
}
